//
//  AFNTool.m
//  Stormbills
//
//  Created by junjun on 2018/7/11.
//  Copyright © 2018年 帝云科技. All rights reserved.
//

#import "AFNTool.h"

@implementation AFNTool
+ (void)PostUrlStr:(NSString *)URLString parameters:(id)parameters showHUD:(id)hudView succeed:(void (^)(id data))succeed nullHandle:(void (^)(id data))nilHandle failure:(void (^)(NSError *error))failure{
    [MBProgressHUD hideHUDForView:hudView animated:YES];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 15;
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",baseUrl, URLString];
    [session POST:urlStr parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        
        if (responseObject == nil) {
            return ;
        }
     
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *dataDict = [AFNTool dictionaryWithJsonString:result];
        NSLog(@"%@  %@",dataDict,dataDict[@"message"]);
        if (dataDict == nil) {
            nilHandle(dataDict);
        }else{
        if ([dataDict[@"status"] intValue] == 9999) {
            succeed(dataDict);
        }else{
            nilHandle(dataDict);
            XHQHUDTEXT(dataDict[@"message"]);
        }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
        NSLog(@"%@",error);
        [MBProgressHUD hideHUDForView:hudView animated:YES];
         XHQHUDTEXT(@"数据请求失败");
    }];
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers  error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

@end
